namespace Crux.Core.LangChain.Abstractions.DocumentLoaders;

/// <summary>
/// 
/// </summary>
public static class EnumerableExtensions
{
    /// <summary>
    ///
    /// </summary>
    private static readonly Dictionary<string, string> Mappings = new(StringComparer.InvariantCultureIgnoreCase)
    {
        {".bmp", "image/bmp"},
        {".gif", "image/gif"},
        {".jpeg", "image/jpeg"},
        {".jpg", "image/jpeg"},
        {".png", "image/png"},
        {".tiff", "image/tiff"},
    };
    /// <summary>
    /// 
    /// </summary>
    /// <param name="texts"></param>
    /// <returns></returns>
    /// <exception cref="ArgumentNullException"></exception>
    public static IReadOnlyList<Document> ToDocuments(this IEnumerable<string> texts)
    {
        texts = texts ?? throw new ArgumentNullException(nameof(texts));

        return texts
            .Select(text => new Document(text))
            .ToList();
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="paths"></param>
    /// <returns></returns>
    /// <exception cref="ArgumentNullException"></exception>
    public static IReadOnlyList<Tuple<string, byte[]>> ToBinaryData(this IEnumerable<string> paths)
    {
        paths = paths ?? throw new ArgumentNullException(nameof(paths));

        var images = new List<Tuple<string, byte[]>>();

        foreach (var path in paths)
        {
            var contentType = GetMimeType(Path.GetExtension(path)) ?? "";
            var image = File.ReadAllBytes(path);

            images.Add(new Tuple<string, byte[]>(contentType, image));
        }

        return images;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="extension"></param>
    /// <returns></returns>
    /// <exception cref="ArgumentNullException"></exception>
    public static string GetMimeType(string extension)
    {
        extension = extension ?? throw new ArgumentNullException(nameof(extension));

        if (!extension.StartsWith("."))
        {
            extension = "." + extension;
        }

        return Mappings.TryGetValue(extension, out var mimeType) switch
        {
            true => mimeType,
            _ => "application/octet-stream"
        };
    }
}